package com;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

import struct.CommentInfo;
import struct.SellerInfo;
import struct.BidHistoryInfo;

import java.util.ArrayList;

@SuppressWarnings("serial")
public class BidHistoryServlet extends HttpServlet 
{
	//client-server style (get input from client, then redirect output)
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException 
	{
		String seller = req.getParameter("seller");
		String itemID = req.getParameter("itemID");
	
		req.setAttribute("seller", seller);
		req.setAttribute("bidders", GetBidders(itemID, seller));
		
		req.getRequestDispatcher("bidHistory.jsp").forward(req, resp);
	}
	
	public ArrayList<BidHistoryInfo> GetBidders(String itemID, String seller)
	{
		
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		ArrayList<BidHistoryInfo> list = new ArrayList<BidHistoryInfo>();
		
		Entity auction;
		try {
			auction = ds.get(KeyFactory.createKey("Auction", Integer.parseInt(itemID)));
			
			Query qBids = new Query("Bid").addFilter("ITEMID", FilterOperator.EQUAL, String.valueOf(auction.getKey().getId())).addSort("TIME", Query.SortDirection.DESCENDING);
			Iterable<Entity> bids = ds.prepare(qBids).asIterable();
			for(Entity bid : bids ){		

				BidHistoryInfo b = new BidHistoryInfo();
				b.bid = bid.getProperty("OFFER").toString();
				String bidder = bid.getProperty("BIDDER").toString();
				
				Entity e;
				try {
					e = ds.get(KeyFactory.createKey("User", bidder));
					
					b.bidder = e.getProperty("FIRSTNAME").toString() + " " +e.getProperty("LASTNAME").toString() ;
					
					b.time = bid.getProperty("TIME").toString();	

					list.add(b);
					
				} catch (EntityNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		} catch (NumberFormatException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (EntityNotFoundException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		return list;
	}
	
	
}